/*
 * @Description: 实时天气组件.本地数据保存6小时，减少去天气平台获取的次数，6小时这个频率是可以配置的
 * @Author: tao.xie
 * @Date: 2019-06-14 11:36:12
 * @Last Modified by: tao.xie
 * @Last Modified time: 2019-06-14 14:16:24
 */
<template>
  <div
    class="wrapper flex-h flex-vc flex-hs"
  >
    <img :src="icon" v-if="weatherLiveData"/>
    <span v-if="weatherLiveData">{{tem}}°C</span>
  </div>
</template>

<script>
import axios from 'axios'
const WEATHER_CACHE_KEY = 'WEATHER_CACHE_KEY_JIADING'// 放入缓存的key
const REFRESH_RATE = 1000 * 3600 * 6 // 6小时，刷新
const REQUEST_URL = 'https://www.tianqiapi.com/api/?version=v6&appid=26751144&appsecret=1PDods9G'
export default {
  mounted() {
    // 首先去取缓存数据
    let cache = window.localStorage.getItem(WEATHER_CACHE_KEY)
    if (cache) {
      // 有，则读取缓存数据
      this.readLocalData(cache)
    } else {
      // 如果没有缓存数据，则实时去取
      this._getWeatherLive()
    }
  },
  data() {
    return {
      tem: '',
      icon: '',
      weatherLiveData: false
    }
  },
  methods: {
    _getWeatherLive: async function () {
      let res = await axios.get(REQUEST_URL)
      if (res.status === 200) {
        let data = res.data
        if (data.wea_img) {
          // 数据返回正常，解析
          this.parseData(data)
        } else {
          // 数据返回异常，加载本地的缓存数据
          this.readLocalDataWhenErr()
        }
      } else {
        // 响应不正常，加载本地的缓存数据
        this.readLocalDataWhenErr()
      }
    },
    parseData(data) { // 解析返回的实时天气数据
      let wea = data.wea_img
      this.tem = data.tem
      this.icon = require('./assets/' + wea + '.png')
      // 更新到缓存
      this.updateToCache(wea, data.tem)
      this.weatherLiveData = true
    },
    updateToCache(wea, tem) {
      // 将温度，天气类型和当前时间时间戳，放入缓存
      let weaObj = {WEA: wea, TEM: tem, TIME: new Date().getTime()}
      window.localStorage.setItem(WEATHER_CACHE_KEY, JSON.stringify(weaObj))
    },
    readLocalData(local, judgeTime = true) {
      let obj = JSON.parse(local)
      let time = obj.TIME
      // 如果需要时间刷新频率的前置条件,且当前的时间减去缓存中数据的置入时间大于规定的刷新周期，则去实时获取天气数据
      if (judgeTime && (new Date().getTime() - time >= REFRESH_RATE)) {
        this._getWeatherLive()
      } else {
        // 否则，加载本地的天气数据，不走实时
        this.tem = obj.TEM
        this.icon = require('./assets/' + obj.WEA + '.png')
        this.weatherLiveData = true
      }
    },
    readLocalDataWhenErr() { // 当实时天气获取失败时，读取本地的数据
      let cache = window.localStorage.getItem(WEATHER_CACHE_KEY)
      if (cache) {
        // 本地有数据，则直接加载本地的数据，并且忽略时间的判断
        this.readLocalData(cache, false)
      } else {
        // 本地无数据，则隐藏
        this.weatherLiveData = false
      }
    }
  }
}
</script>

<style scoped>
.wrapper {
  width: 152px;
  height: 98px;
}
.wrapper > img:first-of-type {
  width: 48px;
  height: 48px;
}
.wrapper > span:first-of-type {
  color: #000000;
  font-size: 12px; /*no*/
  line-height: 17px; /*no*/
  margin-left:16px;
  margin-top:5px;
}
</style>
